/*

 * Copyright (c) 2017-2018, FastDev 刘强 (fastdev@163.com).

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package of.hotswapinject.plugin.imp.perf;


import of.hotswapinject.core.common.Util;

import java.util.*;

public class PerfStatReporter {
    public void send(PerfStack<MethodCallElapse> stack) {
        StringBuilder sb = new StringBuilder();
        Map<String, Long> elapseDict = stack.getElapseDict();
        try {
            List<Map.Entry<String, Long>> list = new ArrayList<Map.Entry<String, Long>>(elapseDict.size());
            for (Map.Entry<String, Long> entry : elapseDict.entrySet()) {
                list.add(entry);
            }

            Collections.sort(list, new Comparator<Map.Entry<String, Long>>() {
                @Override
                public int compare(Map.Entry<String, Long> o1, Map.Entry<String, Long> o2) {
                    return -Long.compare(o1.getValue(), o2.getValue());
                }
            });

            for (Map.Entry<String, Long> entry : list) {
                sb.append("\t").append(entry.getKey()).append("->").append(entry.getValue() / 1000000).append(" ms \n");
            }
            Util.trace("Moniter call report:\n" + sb.toString());
        }
        finally {
            stack.clearElapseDict();
        }
    }
}
